package cocurrent;

import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;

public class IncrementTest {
    /**
     * AtomicInteger(CAS锁),
     * LongAdder(分段CAS锁),
     * Sync（锁升级：1.只有当前线程时，只在对象头上标识线程id，不加锁。2.当有其他线程时，锁被占用时，自旋10次，如果还没抢到锁，继续进行升级。3.重量级锁，需要系统调度切换的介入）
     * 三种自增的速度比较
     *
     * @throws InterruptedException
     * @throws IOException
     */
    @Test
    public void test2() throws InterruptedException, IOException {
        LongAdder longAdder = new LongAdder();

        AtomicInteger atomicInteger = new AtomicInteger();
        long before = System.currentTimeMillis();
        Thread thread = null;
        Runnable runnable = new Runnable() {
            public int num = 0;

            @Override
            public void run() {
                synchronized (this) {
                    for (int i1 = 0; i1 < 100000; i1++) {
                        num++;
                    }

                }

            }
        };
        for (int i = 0; i < 1000; i++) {
//            thread = new Thread(()->{
//                for (int i1 = 0; i1 < 100000; i1++) {
//                    atomicInteger.incrementAndGet();
//                }
//            });//1598
//                        thread = new Thread(()->{
//                            for (int i1 = 0; i1 < 100000; i1++) {
//                                longAdder.increment();
//                            }
//                        });//499

//            thread = new Thread(runnable);//139

            thread.start();
        }

        for (int i = 0; i < 100000; i++) {
            thread.join();
        }
        System.out.println(System.currentTimeMillis() - before);
    }
}
